package com.meirengu.channel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.RongziService;
import com.meirengu.utils.DateUtils;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.MD5Util;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwDfrzPush;
import com.meirengu.webview.model.KwDfrzPushLog;
import com.meirengu.webview.service.KwDfrzPushLogService;
import com.meirengu.webview.service.KwDfrzPushService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 东方融资网
 *
 * @author Mao
 * @create 2017-12-15 12:11
 */
@Service
public class RongziServiceImpl implements RongziService {

    Logger logger = LoggerFactory.getLogger(RongziServiceImpl.class);
    @Autowired
    private KwDfrzPushService kwDfrzPushService;

    @Autowired
    private KwDfrzPushLogService kwDfrzPushLogService;

    public boolean isRegistered(String cellPhoneNumber) {
        boolean flag = false;

        String url = ConfigUtil.getConfig("eastrongzi.is_regist.url");
        String key = ConfigUtil.getConfig("eastrongzi.key");

        String dateStr = (DateUtils.dateToStr(new Date(), "yyyyMMddHHmmss"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CellPhoneNumber", cellPhoneNumber);
        jsonObject.put("TimeStamp", dateStr);
        jsonObject.put("Signature", MD5Util.MD5(cellPhoneNumber + dateStr + key, "utf-8"));

        //接口调用信息表
        KwDfrzPush kwDfrzPush = new KwDfrzPush();
        kwDfrzPush.setInterfaceCode("dfrz-isregister");
        kwDfrzPush.setInterfaceName("东方融资网-是否注册接口");
        kwDfrzPush.setMobile(cellPhoneNumber);
        kwDfrzPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwDfrzPushLog kwDfrzPushLog = new KwDfrzPushLog();
        kwDfrzPushLog.setInterfaceCode("dfrz-isregister");
        kwDfrzPushLog.setInterfaceName("东方融资网-是否注册接口");
        kwDfrzPushLog.setMobile(cellPhoneNumber);
        kwDfrzPushLog.setSendUrl(url.toString());
        kwDfrzPushLog.setParams(jsonObject.toString());

        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPost(url, jsonObject.toString());
            int code = hr.getStatusCode();
            if (code == 200) {
                kwDfrzPushLog.setBackUrl(hr.toString());
                kwDfrzPushLog.setHttpCode(200);
                kwDfrzPushLog.setHttpContent(hr.toString());

                logger.info("==RongziServiceImpl.IsRegistered request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String rCode = returnMsg.getString("Code");
                Boolean rIsRegistered = returnMsg.getBoolean("IsRegistered");
                if ("0".equals(rCode) && rIsRegistered != null && !rIsRegistered.booleanValue()) {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    kwDfrzPush.setMessage("成功");
                    flag = true;
                    logger.info("==RongziServiceImpl.IsRegistered business success");
                } else if ("0".equals(rCode) && rIsRegistered != null && rIsRegistered.booleanValue()) {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_REPEAT);
                    kwDfrzPush.setMessage("用户已注册");
                    logger.warn("==RongziServiceImpl.IsRegistered business fail");
                } else if ("1".equals(rCode)) {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_FAIL);
                    kwDfrzPush.setMessage("失败");
                    logger.warn("==RongziServiceImpl.IsRegistered business fail");
                } else if ("3".equals(rCode)) {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_SIGNATURE_ERROR);
                    kwDfrzPush.setMessage("签名不合法 ");
                    logger.warn("==RongziServiceImpl.IsRegistered business fail");
                } else {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwDfrzPush.setMessage("其他原因");
                    logger.warn("==RongziServiceImpl.IsRegistered business fail");
                }
            } else {
                kwDfrzPushLog.setBackUrl(hr.toString());
                kwDfrzPushLog.setHttpCode(code);
                kwDfrzPushLog.setHttpContent(hr.toString());
                logger.warn("==RongziServiceImpl.IsRegistered request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwDfrzPushLog.setHttpCode(408);
            kwDfrzPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwDfrzPushService.insert(kwDfrzPush);
            kwDfrzPushLog.setPushId(kwDfrzPush.getId());
            kwDfrzPushLogService.insert(kwDfrzPushLog);
        }

        return flag;
    }

    /**
     * 标准
     * code=0，IsRegistered=false 未注册  code=0，IsRegistered=true 已注册
     * <p>
     * 第一次注册返回
     * "IsRegistered":false,
     * "Token":"cef22f1d-e184-4c58-be00-607161fa717b",
     * "Code":"0",
     * "TimeStamp":"20171222190021",
     * "Signature":"6586e1cbd8531438bf51485cabe917f1"
     * <p>
     * 已注册返回
     * "IsRegistered":true,
     * "Token":"5dec7c29-1dac-4321-bfc2-e552331fb963",
     * "Code":"0",
     * "TimeStamp":"20171222194833",
     * "Signature":"3238b14ad09f0c4ee23c032c8ed4ad3a"
     *
     * @param cellPhoneNumber
     * @return
     * @throws Exception
     */
    public Integer registered(String cityName, String cellPhoneNumber, String realName, int gender,
                              int loanAmount, int age, int haveHouseLoan, int haveCarLoan,
                              int socialSecurityFund, int haveCreditCard, int identity,
                              int incomeDistributionType, int workingAge, int averageMonthlyIncome,
                              String workingCity, int creditCardAmount, int haveHouse, int haveCar) throws Exception {
        //调用是否注册接口判断用户是否注册
        if (!isRegistered(cellPhoneNumber)) {
            return 0;
        }
        String url = ConfigUtil.getConfig("eastrongzi.regist.url");
        String key = ConfigUtil.getConfig("eastrongzi.key");
        String utmsource = ConfigUtil.getConfig("eastrongzi.utmsource");
        String dateStr = (DateUtils.dateToStr(new Date(), "yyyyMMddHHmmss"));
        int utmSource = Integer.parseInt(utmsource);
        String cityNamePY = "";
        switch (cityName) {
            case "上海":
                cityNamePY = "SHANGHAI";
                break;
            case "苏州":
                cityNamePY = "SUZHOU";
                break;
            case "无锡":
                cityNamePY = "WUXI";
                break;
            case "南京":
                cityNamePY = "NANJING";
                break;
            case "杭州":
                cityNamePY = "HANGZHOU";
                break;
            case "宁波":
                cityNamePY = "NINGBO";
                break;
            case "广州":
                cityNamePY = "GUANGZHOU";
                break;
            case "深圳":
                cityNamePY = "SHENZHEN";
                break;
            case "青岛":
                cityNamePY = "QINGDAO";
                break;
            case "成都":
                cityNamePY = "CHENGDU";
                break;
            case "北京":
                cityNamePY = "BEIJING";
                break;
            case "武汉":
                cityNamePY = "WUHAN";
                break;
            case "天津":
                cityNamePY = "TIANJIN";
                break;
        }
        JSONObject jsonObject = new JSONObject();


        jsonObject.put("CityName", cityNamePY);
        jsonObject.put("CellPhoneNumber", cellPhoneNumber);
        jsonObject.put("RealName", realName);
        jsonObject.put("Gender", gender);
        jsonObject.put("LoanAmount", loanAmount);
        jsonObject.put("UtmSource", utmSource);
        jsonObject.put("TimeStamp", dateStr);
        jsonObject.put("Signature", MD5Util.MD5(cityNamePY + cellPhoneNumber + realName
                + gender + loanAmount + utmSource + dateStr + key, "utf-8"));
        jsonObject.put("Age", age);
        jsonObject.put("HaveHouseLoan", haveHouseLoan);
        jsonObject.put("HaveCarLoan", haveCarLoan);
        jsonObject.put("SocialSecurityFund ", socialSecurityFund);
        jsonObject.put("HaveCreditCard ", haveCreditCard);
        jsonObject.put("Identity", identity);
        jsonObject.put("IncomeDistributionType ", incomeDistributionType);
        jsonObject.put("WorkingAge", workingAge);
        jsonObject.put("AverageMonthlyIncome", averageMonthlyIncome);
        jsonObject.put("WorkingCity", cityNamePY);
        jsonObject.put("CreditCardAmount", creditCardAmount);
        jsonObject.put("HaveHouse", haveHouse);
        jsonObject.put("HaveCar", haveCar);

        //接口调用信息表
        KwDfrzPush kwDfrzPush = new KwDfrzPush();
        kwDfrzPush.setInterfaceCode("dfrz");
        kwDfrzPush.setInterfaceName("东方融资网");
        kwDfrzPush.setMobile(cellPhoneNumber);
        kwDfrzPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwDfrzPushLog kwDfrzPushLog = new KwDfrzPushLog();
        kwDfrzPushLog.setInterfaceCode("dfrz");
        kwDfrzPushLog.setInterfaceName("东方融资网");
        kwDfrzPushLog.setMobile(cellPhoneNumber);
        kwDfrzPushLog.setSendUrl(url.toString());
        kwDfrzPushLog.setParams(jsonObject.toString());


        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPost(url, jsonObject.toString());
            int code = hr.getStatusCode();
            kwDfrzPushLog.setBackUrl(hr.toString());
            kwDfrzPushLog.setHttpCode(code);
            kwDfrzPushLog.setHttpContent(hr.toString());
            if (code == 200) {
                logger.info("==RongziServiceImpl.registered request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String rCode = returnMsg.getString("Code");
                Boolean rIsRegistered = returnMsg.getBoolean("IsRegistered");
                if ("0".equals(rCode) && rIsRegistered != null && !rIsRegistered.booleanValue()) {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    kwDfrzPush.setMessage("成功");
                    logger.info("==RongziServiceImpl.registered business success");
                } else if ("0".equals(rCode) && rIsRegistered != null && rIsRegistered.booleanValue()) {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_REPEAT);
                    kwDfrzPush.setMessage("用户已注册");
                    logger.warn("==RongziServiceImpl.registered business fail");
                } else if ("1".equals(rCode)) {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_FAIL);
                    kwDfrzPush.setMessage("失败");
                    logger.warn("==RongziServiceImpl.registered business fail");
                } else if ("3".equals(rCode)) {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_SIGNATURE_ERROR);
                    kwDfrzPush.setMessage("签名不合法 ");
                    logger.warn("==RongziServiceImpl.registered business fail");
                } else {
                    kwDfrzPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwDfrzPush.setMessage("其他原因");
                    logger.warn("==RongziServiceImpl.IsRegistered business fail");
                }
            } else {
                kwDfrzPushLog.setBackUrl(hr.toString());
                kwDfrzPushLog.setHttpCode(code);
                kwDfrzPushLog.setHttpContent(hr.toString());
                logger.warn("==RongziServiceImpl.registered request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwDfrzPushLog.setHttpCode(408);
            kwDfrzPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwDfrzPushService.insert(kwDfrzPush);
            kwDfrzPushLog.setPushId(kwDfrzPush.getId());
            kwDfrzPushLogService.insert(kwDfrzPushLog);
            return kwDfrzPush.getCode();
        }
    }
}
